package com.example.muasic.activity;


import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.muasic.R;
import com.example.muasic.adapter.AlphaTransformer;
import com.example.muasic.adapter.MyVpAdater;
import com.example.muasic.fragment.QuickControlsFragment;
import com.example.muasic.info.Info;
import com.example.muasic.provider.MusicSqLiteHelper;
import com.example.muasic.service.IService;
import com.example.muasic.service.MusicService;
import com.example.muasic.uitl.utils;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class PlayingActivity extends AppCompatActivity implements View.OnClickListener {

    private final static String TAG = "sorrower";

    private ImageView mplay;
    private ImageView mpre;
    private ImageView mnext;
    private ImageView mode;
    private ImageView back;
    private ObjectAnimator mNeedleAnim;
    private static ObjectAnimator discObjectAnimator;
    private ImageView mNeedle;
    private static ViewPager viewPager;
    private static TextView songName;
    private static TextView artistName;
    private static ImageView fav;
    private static TextView time1;
    private static int playMode;
    private static int choose;
    private static int panduan;
    private static TextView time2;
    private static IService iService;
    private static SeekBar sb_progress;
    private static String mFile;
    private static Context context;
    private static MyVpAdater adater;
    private ServiceConnection conn;
    private static int mFilePath=0;
    private static List<Bitmap> musicImg;
    private static Info music1;
    public static final int STATE_PLAYING = 1;//正在播放
    public static final int STATE_PAUSE = 2;//暂停
    public static final int STATE_STOP = 3;//停止
    public static int mState;
    private static MusicSqLiteHelper musicSqLiteHelper;

    private static List<Info> musicList;
//    private static List<Bitmap> prebitList;
//    private static List<Bitmap> musicImg;

    private static int mupiaying = 0;

    public static void playMusic() {
        if (mState == STATE_STOP) {
            discObjectAnimator.start();//动画开始
            mState = STATE_PLAYING;
        } else if (mState == STATE_PAUSE) {
            discObjectAnimator.resume();//动画重新开始
            mState = STATE_PLAYING;
        } else if (mState == STATE_PLAYING) {
            discObjectAnimator.pause();//动画暂停
            mState = STATE_PAUSE;
        }
    }


    //更新进度条时间
    private static void updateTime(TextView textView,int millisecond){
        int second = millisecond/1000;
        int hh = second / 3600;
        int mm = second % 3600 / 60;
        int ss = second % 60;

        String str = null;
        if(hh!=0){
            str = String.format("%02d:%02d:%02d",hh,mm,ss);
        }else {
            str = String.format("%02d:%02d",mm,ss);
        }

        textView.setText(str);

    }

    //从Service获取进度条信息
    public static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle data = msg.getData();
            int duration = data.getInt("duration");
            int currentPosition = data.getInt("currentPosition");
            sb_progress.setMax(duration);
            sb_progress.setProgress(currentPosition);
            updateTime(time1,currentPosition);
            updateTime(time2,duration);
        }
    };
    //每次 播放 调用的方法
    public static void playing(String mFile1,IService iService ){
        iService.callNowMusic(mFilePath);
        iService.callPlayMusic(mFile1);

        iService.callgetMediaPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                setNext();
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playing);
        musicSqLiteHelper = new MusicSqLiteHelper(this,"music.db",1);



        View cv = getWindow().getDecorView();
        context=cv.getContext();

        Bundle buddle = this.getIntent().getExtras();
        musicList = (List<Info>)buddle.get("musiclist");
        mFilePath = (int) buddle.get("music_send");
        back = findViewById(R.id.iv_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlayingActivity.this.finish();
            }
        });
        Bitmap bit=null;
        musicImg=new ArrayList<>();
        for(int i=0;i<musicList.size();i++){
            musicImg.add(bit);
        }
       /* prebitList = (List<Bitmap>) buddle.get("prebitlist");
        panduan = (int) buddle.get("panduan_send");*/



       //开启服务
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);

        conn = new ServiceConnection(){
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //6. 获取IBinder对象, 以此调用暴露的函数
                iService = (IService) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        };

          // 绑定服务
        bindService(intent, conn, BIND_AUTO_CREATE);


        sb_progress=(SeekBar)findViewById(R.id.play_seek);

        // 设置进度条拖动事件
        sb_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                iService.callSeekToPos(seekBar.getProgress());
                if(mupiaying==2){
                    mplay.setImageResource(R.drawable.play_rdi_btn_pause);
                    iService.callConMusic();
                    mupiaying=1;
                }
            }
        });

        initUI();
        try {
            setAlbum();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }

    private void setAlbum() throws FileNotFoundException {
        /*MusicItemAdapter adapter = new MusicItemAdapter(this, R.layout.activity_play_music, musicList);
        viewPager.setAdapter(adapter);*/
        viewPager.setPageMargin(80);
        viewPager.setOffscreenPageLimit(3);
        discObjectAnimator.start();


      /*  if(panduan==1){
            musicImg=utils.getImg(context, musicList);
        }else {
            if(prebitList.size()>0) {
                musicImg = prebitList;
            }else {
                musicImg=utils.getImg(context, musicList);
            }
        }
        MusicService.setNowBitList(musicImg);*/

        Bitmap bitmap =utils.getAlbumArt(context,musicList.get(mFilePath).getAlbumId());
        musicImg.set(mFilePath,bitmap);
        adater = new MyVpAdater(context, musicImg);
        viewPager.setAdapter(adater);
        /*viewPager.setCurrentItem(mFilePath, false);*/
        viewPager.setPageTransformer(false,new AlphaTransformer());
        viewPager.setCurrentItem(mFilePath, false);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                Log.d("Playing","第"+i+"行");

                mFilePath = i;
                mplay.setImageResource(R.drawable.play_rdi_btn_pause);
                if (musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())==1){
                    fav.setImageResource(R.drawable.play_icn_loved);
                }else if(musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())!=1){
                    fav.setImageResource(R.drawable.play_rdi_icn_love);
                }
                songName.setText(musicList.get(mFilePath).getMusicName());
                artistName.setText(musicList.get(mFilePath).getArtist());
                if(musicSqLiteHelper.searchRecMusic(musicList.get(mFilePath).getSongId())==1) {
                    musicSqLiteHelper.deleteRecMusic(musicList.get(mFilePath).getSongId());
                    musicSqLiteHelper.addRecMusic(musicList.get(mFilePath));
                }else if(musicSqLiteHelper.searchRecMusic(musicList.get(mFilePath).getSongId())!=1) {
                    musicSqLiteHelper.addRecMusic(musicList.get(mFilePath));
                }


                Bitmap bitmap = null;
                try {
                    Log.i("bit","成功");
                    bitmap = utils.getAlbumArt(context,musicList.get(mFilePath).getAlbumId());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                musicImg.set(mFilePath,bitmap);
                adater.notifyDataSetChanged();
                QuickControlsFragment.setPosition(mFilePath);
                QuickControlsFragment.setmusicList(musicList);
                QuickControlsFragment.updateNowplayingCard();
                mNeedleAnim.start();
                mState = STATE_STOP;
                playMusic();

                playing(musicList.get(mFilePath).getData(),iService);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }





    /**
     * 初始化ui
     */
    @SuppressLint("WrongConstant")
    private void initUI() {
        mplay = (ImageView) findViewById(R.id.playing_play);
        mpre = (ImageView) findViewById(R.id.playing_pre);
        mnext = (ImageView) findViewById(R.id.playing_next);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        time1 = (TextView) findViewById(R.id.music_duration_played);
        time2 = (TextView) findViewById(R.id.music_duration);
        songName = (TextView) findViewById(R.id.song_name);
        artistName = (TextView) findViewById(R.id.artist_name);
        //唱片旋转
        mState = STATE_PLAYING;
        discObjectAnimator = ObjectAnimator.ofFloat(viewPager, "rotation", 0, 360);
        discObjectAnimator.setDuration(20000);
        //使ObjectAnimator动画匀速平滑旋转
        discObjectAnimator.setInterpolator(new LinearInterpolator());
        //无限循环旋转
        discObjectAnimator.setRepeatCount(ValueAnimator.INFINITE);
        discObjectAnimator.setRepeatMode(ValueAnimator.INFINITE);


        if(musicSqLiteHelper.searchRecMusic(musicList.get(mFilePath).getSongId())==1) {
            musicSqLiteHelper.deleteRecMusic(musicList.get(mFilePath).getSongId());
            musicSqLiteHelper.addRecMusic(musicList.get(mFilePath));
        }else if(musicSqLiteHelper.searchRecMusic(musicList.get(mFilePath).getSongId())!=1) {
            musicSqLiteHelper.addRecMusic(musicList.get(mFilePath));
        }

        songName.setText(musicList.get(mFilePath).getMusicName());
        artistName.setText(musicList.get(mFilePath).getArtist());
        mNeedle=(ImageView)findViewById(R.id.needle);
        mNeedleAnim = ObjectAnimator.ofFloat(mNeedle, "rotation", -30, 0);
        mNeedleAnim.setDuration(200);
        mNeedleAnim.setRepeatMode(0);
        mNeedleAnim.setInterpolator(new LinearInterpolator());


        mode = (ImageView) findViewById(R.id.playing_mode);
        fav = (ImageView) findViewById(R.id.playing_fav);
        if (musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())==1){
            fav.setImageResource(R.drawable.play_icn_loved);
        }
        if(playMode==0){
            mode.setImageResource(R.drawable.play_icn_loop_prs);
        }else if(playMode==1){
            mode.setImageResource(R.drawable.play_icn_one_prs);
        }else if (playMode==2){
            mode.setImageResource(R.drawable.play_icn_shuffle);
        }
        mupiaying=1;
        QuickControlsFragment.setpalying(1);
        sb_progress = (SeekBar) findViewById(R.id.play_seek);
        mplay.setOnClickListener(this);
        mpre.setOnClickListener(this);
        mnext.setOnClickListener(this);
        mode.setOnClickListener(this);
        fav.setOnClickListener(this);
    }

    //按钮点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.playing_mode:
                if(playMode==0){
                    playMode=1;
                    iService.callgetplaymode(playMode);
                    mode.setImageResource(R.drawable.play_icn_one_prs);
                }else if(playMode==1){
                    playMode=2;
                    iService.callgetplaymode(playMode);
                    mode.setImageResource(R.drawable.play_icn_shuffle);
                }else if (playMode==2){
                    playMode=0;
                    iService.callgetplaymode(playMode);
                    mode.setImageResource(R.drawable.play_icn_loop_prs);
                }
                break;
            case R.id.playing_play:
                if(mupiaying==0){
                    mplay.setImageResource(R.drawable.play_rdi_btn_pause);
                    playing(musicList.get(mFilePath).getData(),iService);
                    QuickControlsFragment.setpalying(1);
                }else if(mupiaying==1){
                   QuickControlsFragment.setpalying(2);
                   Toast.makeText(this, "第" + mFilePath + "行", Toast.LENGTH_LONG).show();
                    mplay.setImageResource(R.drawable.play_rdi_btn_play);
                   mNeedleAnim.reverse();
                    mState = STATE_PLAYING;
                   playMusic();
                    iService.callPauseMusic();
                   mupiaying=2;
                }
                else if(mupiaying==2){
                    mplay.setImageResource(R.drawable.play_rdi_btn_pause);

                    mState = STATE_PAUSE;
                    playMusic();
                    mNeedleAnim.start();
                    iService.callConMusic();
                   QuickControlsFragment.setpalying(1);
                    mupiaying=1;
                }
                break;
            case R.id.playing_next:
                choose=2;
                Log.i(TAG, "bt_next");
                if(mupiaying==2){
                    mplay.setImageResource(R.drawable.play_rdi_btn_pause);
                    mupiaying=1;
                }
                play();
                break;
            case R.id.playing_pre:
                choose=1;
                if(mupiaying==2){
                mplay.setImageResource(R.drawable.play_rdi_btn_pause);
                mupiaying=1;
                }
                play();
                Log.i(TAG, "bt_pre");
                break;
            case R.id.playing_fav:
                mFilePath = iService.callgetNowMusic();
                if(musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())==1){
                    musicSqLiteHelper.deleteFavMusic(musicList.get(mFilePath).getSongId());
                    fav.setImageResource(R.drawable.play_rdi_icn_love);
                }else if(musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())!=1){
                    musicSqLiteHelper.addFavMusic(musicList.get(mFilePath));
                    fav.setImageResource(R.drawable.play_icn_loved);
                }
                break;
        }
    }


    //设定自动播放完后的下一首歌
    private static void setNext(){
        if (playMode == 0)//全部循环
        {
            if (mFilePath == musicList.size() - 1)//默认循环播放
            {
                mFilePath = 0;// 第一首

            } else {
                mFilePath++;
            }
        } else if (playMode == 1)//单曲循环
        {

        } else if (playMode == 2)//随机
        {
            mFilePath = (int) (Math.random() * musicList.size());//随机播放
        }

        if (musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())==1){
            fav.setImageResource(R.drawable.play_icn_loved);
        }else if(musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())!=1){
            fav.setImageResource(R.drawable.play_rdi_icn_love);
        }
        if(musicSqLiteHelper.searchRecMusic(musicList.get(mFilePath).getSongId())==1) {
            musicSqLiteHelper.deleteRecMusic(musicList.get(mFilePath).getSongId());
            musicSqLiteHelper.addRecMusic(musicList.get(mFilePath));
        }else if(musicSqLiteHelper.searchRecMusic(musicList.get(mFilePath).getSongId())!=1) {
            musicSqLiteHelper.addRecMusic(musicList.get(mFilePath));
        }
        songName.setText(musicList.get(mFilePath).getMusicName());
        artistName.setText(musicList.get(mFilePath).getArtist());

        Bitmap bitmap = null;
        try {
            Log.i("bit","成功");
            bitmap = utils.getAlbumArt(context,musicList.get(mFilePath).getAlbumId());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        musicImg.set(mFilePath,bitmap);
        adater.notifyDataSetChanged();
        viewPager.setCurrentItem(mFilePath, false);

        QuickControlsFragment.setPosition(mFilePath);
        QuickControlsFragment.setmusicList(musicList);
        QuickControlsFragment.updateNowplayingCard();
        mState = STATE_STOP;

        playMusic();
        playing(musicList.get(mFilePath).getData(),iService);
    }

    //上一首或者下一首播放
    private void play(){
        if (playMode == 0||playMode == 1)//全部循环或单曲循环
        {
            if (mFilePath == musicList.size() - 1)
            {
                if (choose == 1) {
                    mFilePath--;
                } else if (choose == 2) {
                    mFilePath = 0;// 第一首
                }
            } else if (mFilePath == 0) {
                if (choose == 1) {
                    mFilePath = musicList.size() - 1;
                } else if (choose == 2) {
                    mFilePath++;
                }
            }else {
                if(choose ==1){
                    mFilePath--;
                }else if(choose ==2){
                    mFilePath++;
                }
            }

        } else if (playMode == 2)//随机
        {
            mFilePath = (int) (Math.random() * musicList.size());//随机播放

        }

        if (musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())==1){
            fav.setImageResource(R.drawable.play_icn_loved);
        }else if(musicSqLiteHelper.searchFavMusic(musicList.get(mFilePath).getSongId())!=1){
            fav.setImageResource(R.drawable.play_rdi_icn_love);
        }
        songName.setText(musicList.get(mFilePath).getMusicName());
        artistName.setText(musicList.get(mFilePath).getArtist());
        if(musicSqLiteHelper.searchRecMusic(musicList.get(mFilePath).getSongId())==1) {
            musicSqLiteHelper.deleteRecMusic(musicList.get(mFilePath).getSongId());
            musicSqLiteHelper.addRecMusic(musicList.get(mFilePath));
        }else if(musicSqLiteHelper.searchRecMusic(musicList.get(mFilePath).getSongId())!=1) {
            musicSqLiteHelper.addRecMusic(musicList.get(mFilePath));
        }
        Toast.makeText(this, "第" + mFilePath + "行", Toast.LENGTH_LONG).show();

        Bitmap bitmap = null;
        try {
            Log.i("bit","成功");
            bitmap = utils.getAlbumArt(context,musicList.get(mFilePath).getAlbumId());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        musicImg.set(mFilePath,bitmap);
        viewPager.setCurrentItem(mFilePath, false);
        adater.notifyDataSetChanged();
        QuickControlsFragment.setPosition(mFilePath);
        QuickControlsFragment.setmusicList(musicList);
        QuickControlsFragment.updateNowplayingCard();
        mState = STATE_STOP;
        playMusic();
        mNeedleAnim.start();
        playing(musicList.get(mFilePath).getData(),iService);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }
}

